//
//  XBridge.m
//  JSTest
//
//  Created by 奇林刘 on 2018/9/30.
//  Copyright © 2018年 奇林刘. All rights reserved.
//

#import "XBridge.h"

@interface XBridge () <WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate>

@property (nonatomic, weak) XBridgeWebView *managingWebView;

@end

@implementation XBridge {
    id _receivedMessageBody;
}

#pragma mark - XBridge
- (void)manageWebView:(XBridgeWebView *)webView {
    self.managingWebView = webView;
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    [[webView configuration].userContentController addScriptMessageHandler:self name:ScriptMessageName];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
}

- (void)abandonWebView:(XBridgeWebView *)webView {
    [webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [[webView configuration].userContentController removeScriptMessageHandlerForName:ScriptMessageName];
}

#pragma mark - delegate
//WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"\nReceiveScriptMessageFromWebView: { \n name=%@\n body=%@\n}", message.name, message.body);
    if ([message.name isEqualToString:ScriptMessageName]) {
        _receivedMessageBody = message.body;
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"XBridge_Property" ofType:@"plist"];
        NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
        NSString *method = dic[message.body[@"methodName"]];
        if (method) [self performSelector:NSSelectorFromString(method)];
    }
}
//WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSString *url = webView.URL.absoluteString;
    NSLog(@"%@", url);
    [SVProgressHUD dismiss];
}

//WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    [self alertMessage:message completionHandler:completionHandler];
}

//KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqual:@"estimatedProgress"] && object == self.managingWebView) {
        [self.managingWebView.progressView setAlpha:1.0f];
        [self.managingWebView.progressView setProgress:self.managingWebView.estimatedProgress animated:YES];
        if (self.managingWebView.estimatedProgress  >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.managingWebView.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.managingWebView.progressView setProgress:0.0f animated:YES];
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 相关方法
//获取当前VC
- (UIViewController *)getCurrentVC {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]) {
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        currentVC = rootVC;
    }
    return currentVC;
}

//alert
- (void)alertMessage:(NSString *)message completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }];
    [alertController addAction:alertAction];
    
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 实现单例
static XBridge *_instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}

+ (instancetype)shareXBridge {
    return [[self alloc] init];
}

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}




@end
